package org.dfzt.config.filter;

import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dfzt.common.util.XssFilterUtil;
import org.dfzt.common.util.encryption.SMUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpHelper {
    /**
     * 处理 post 请求体参数
     *
     * @param request
     * @return
     */
    public static String getBodyString(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        String result = "";
        BufferedReader reader=null;
        try {
            int len = request.getContentLength();
            if (len != -1) {
                reader = request.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                result = sb.toString();
                JSONObject job = JSON.parseObject(result);
                if(job!=null){
                    for(String key:job.keySet()){
                        job.put(key,SMUtils.sm2Decrypt(job.getString(key)));
                    }
                    result=job.toJSONString();
                }
            }
        } catch (Exception e) {
            try {
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
        //xss
        result = XssFilterUtil.clean(result);

        return result==null?"":result;
    }

    /**
     * 处理 get 方式请求参数
     *
     * @param request
     * @return
     */
    public static Map<String, String[]> getParamMap(HttpServletRequest request) {
        Map<String, String[]> map=new HashMap<>();
        String result = URLUtil.decode(request.getQueryString());
        if(result!=null){
            String[] split = result.split("&");
            for (String str:split) {
                if(str.contains("=")){
                    String key=str.substring(0,str.indexOf("="));
                    String value=str.substring(str.indexOf("=")+1);
                    key=XssFilterUtil.clean(key);
                    if(key.equals("_t")){
                        request.setAttribute(key, value);
                        map.put(key,new String[]{value});
                    }else{
                        String decrypt=SMUtils.sm2Decrypt(value);
                        request.setAttribute(key, decrypt);
                        map.put(key,new String[]{decrypt});
                    }
                }
            }
        }

        return map;
    }
}
